import { login, logout, getRoutes, getInfo } from '@/api/admin'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, setAsyncRoutes } from '@/router'
import crypto from 'crypto'
// import store from '@/store'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // console.log(userInfo)

    const { user_name, password } = userInfo
    return new Promise((resolve, reject) => {
      const md5 = crypto.createHash('md5')
      md5.update(password)
      const new_password = md5.digest('hex')
      login({ user_name: user_name.trim(), password: new_password }).then((response) => {
        // console.log('response', response)

        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user routes
  getRoutes() {
    return new Promise((resolve, reject) => {
      getRoutes().then((response) => {
        const { routes } = response

        if (!routes) {
          reject('获取路径信息失败，请重新登陆')
        }

        resolve(routes)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { name, introduction, avatar, roles } = response

        if (!name) {
          reject('验证失败，请重新登陆')
        }

        // 验证是否有返回角色数组数据
        if (!roles || roles.length <= 0) {
          reject('用户角色数据不能为空')
        }

        commit('SET_NAME', name)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        resolve({ roles })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])

        removeToken() // must remove  token  first
        resetRouter()
        setAsyncRoutes([])

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])

      removeToken() // must remove  token  first
      resolve()
    })
  }

  // dynamically modify permissions
  // changeRoles({ commit, dispatch }, role) {
  //   return new Promise(async resolve => {
  //     const token = role + '-token'

  //     commit('SET_TOKEN', token)
  //     setToken(token)

  //     const { roles } = await dispatch('getInfo')

  //     resetRouter()

  //     // generate accessible routes map based on roles
  //     const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

  //     // dynamically add accessible routes
  //     router.addRoutes(accessRoutes)

  //     // reset visited views and cached views
  //     dispatch('tagsView/delAllViews', null, { root: true })

  //     resolve()
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

